
const ticketQueryController = function(HttpService, $state) {
  'ngInject';

  const vm = this;

  vm.searchCriteria = {
    keyword: '',
    status: '',
    priority: '',
    category: '',
    assignee: '',
    dateFrom: '',
    dateTo: ''
  };

  // 数据初始化
  vm.tickets = [];
  vm.filteredTickets = [];
  vm.isLoading = false;
  vm.pagination = {
    page: 1,
    size: 20,
    total: 0
  };

  // 选项数据
  vm.statusOptions = ['pending', 'in_progress', 'resolved', 'closed', 'cancelled'];
  vm.priorityOptions = ['low', 'medium', 'high', 'urgent'];
  vm.categoryOptions = [];
  vm.assigneeOptions = [];

  // 初始化
  vm.$onInit = function() {
    loadTicketOptions();
    loadTickets();
  };

  // 加载工单选项数据
  function loadTicketOptions() {
    HttpService.get('/api/tickets/options')
      .then(response => {
        if (response.success) {
          if (response.data.categories) {
            vm.categoryOptions = response.data.categories;
          }
          if (response.data.supportStaff) {
            vm.assigneeOptions = response.data.supportStaff;
          }
        }
      })
      .catch(error => {
        console.error('加载工单选项失败:', error);
      });
  }

  // 加载工单列表
  function loadTickets() {
    vm.isLoading = true;
    
    // 构建查询参数
    const params = {
      page: vm.pagination.page,
      size: vm.pagination.size,
      ...vm.searchCriteria
    };

    // 清除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    HttpService.get('/api/tickets', { params })
      .then(response => {
        if (response.success) {
          vm.tickets = response.data.tickets || [];
          vm.filteredTickets = vm.tickets;
          vm.pagination.total = response.data.total || 0;
        } else {
          alert('获取工单列表失败：' + response.message);
        }
      })
      .catch(error => {
        alert('获取工单列表失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  }

  vm.search = function() {
    vm.pagination.page = 1; // 重置到第一页
    loadTickets();
  };

  vm.reset = function() {
    vm.searchCriteria = {
      keyword: '',
      status: '',
      priority: '',
      category: '',
      assignee: '',
      dateFrom: '',
      dateTo: ''
    };
    vm.pagination.page = 1;
    loadTickets();
  };

  vm.getStatusClass = function(status) {
    const statusClasses = {
      'pending': 'badge-warning',
      'in_progress': 'badge-info',
      'resolved': 'badge-success',
      'closed': 'badge-secondary',
      'cancelled': 'badge-danger'
    };
    return statusClasses[status] || 'badge-secondary';
  };

  vm.getPriorityClass = function(priority) {
    const priorityClasses = {
      'low': 'badge-success',
      'medium': 'badge-info',
      'high': 'badge-warning',
      'urgent': 'badge-danger'
    };
    return priorityClasses[priority] || 'badge-secondary';
  };

  // 导航到工单详情页面
  vm.viewDetails = function(ticket) {
    $state.go('app.ticketDetail', { id: ticket.id });
  };

  // 刷新列表
  vm.refresh = function() {
    loadTickets();
  };
};

const ticketQueryComponent = {
  templateUrl: 'src/app/pages/ticket-query/ticket-query.template.html',
  controller: ticketQueryController
};

function initTicketQueryController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化工单查询控制器模块');
    return;
  }

  angular.module('app.pages.ticketQuery', [])
    .component('ticketQueryPage', ticketQueryComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initTicketQueryController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initTicketQueryController();
}